<template>
  <SuperTable
    ref="superTableRef"
    search
    pager
    border
    align="center"
    :columns="columns"
    :data-request="fetchData"
    :export-config="{}"
    header-title="样本共享"
    @checkbox-change="checkboxChangeFn"
    @checkbox-all="checkboxChangeFn"
  >
    <template #action>
      <!--      <span style="width: 130px; margin-right: 10px">-->
      <!--        当前状态：{{ { 1: '共享', 2: '已入库未共享' }[state.shareState] }}-->
      <!--      </span>-->
      <span class="check-num">
        当前已选中
        <span style="margin: 0 5px; color: #1f59f7">{{ state.checkedList.length }}</span>
        条数据
      </span>
      <Popconfirm v-if="state.shareState === 1" :disabled="!state.checkedList.length" :title="`确认取消共享${state.checkedList.length}条数据吗？`" @confirm="putSampleUnSharingFn">
        <Button :disabled="!state.checkedList.length" type="primary">取消共享</Button>
      </Popconfirm>
      <Popconfirm :disabled="!state.checkedList.length" :title="`确认将${state.checkedList.length}条数据添加到共享收藏吗？`" @confirm="getAddMyCollectionFn">
        <Button :disabled="!state.checkedList.length" type="primary">添加到共享收藏</Button>
      </Popconfirm>
      <Popconfirm v-if="state.shareState === 2" :disabled="!state.checkedList.length" :title="`确认取消共享${state.checkedList.length}条数据吗？`" @confirm="putSampleUnSharingFn">
        <Button :disabled="!state.checkedList.length" type="primary">共享</Button>
      </Popconfirm>
      <Button v-if="state.shareState === 1" :disabled="!state.checkedList.length" type="primary" @click="generateApprovalTicketFn">生成审批单</Button>
      <Button v-if="state.shareState === 1" :disabled="!state.checkedList.length" type="primary" @click="outboundFn">出库</Button>
    </template>
  </SuperTable>
  <SampleSeeModal v-model:show-modal="state.showSampleSeeModal" :data="state.currentData" :id="state.currentData?.specimenId" />
  <ApprovalSlipModal v-model:show-modal="state.showApprovalSlipModal" :data="state.checkedList" />
</template>

<script setup lang="ts">
import SuperTable from '@/framework/components/core/super-table/super-table.vue';
import ApprovalSlipModal from '@/modules/share-management/components/approval-slip-modal.vue';
import SampleSeeModal from '@/components/sample-see-modal/sample-see-modal.vue';
import type { TableColumnItem } from './columns';
import { VxeGridPropTypes } from 'vxe-table';
import { baseColumns } from './columns';
import { reactive, ref } from 'vue';
import { Button, Select, Popconfirm, message } from 'ant-design-vue';
import { getUnSharedData, getSharedData, putSampleSharing, putSampleUnSharing, getAddMyCollection } from '../../api/sample-sharing';
import router from '@/router';

type state = {
  shareState: 1 | 2;
  showSampleSeeModal: boolean;
  showApprovalSlipModal: boolean;
  checkedList: any[];
  currentData: any;
};

/**
 * data
 */
const state: state = reactive({
  shareState: 1,
  showSampleSeeModal: false,
  showApprovalSlipModal: false,
  checkedList: [],
  currentData: {},
} as state);

/**
 * table
 */
const superTableRef = ref<InstanceType<typeof SuperTable>>();
const columns: TableColumnItem[] = [
  ...baseColumns,
  {
    title: '操作',
    field: '$action',
    hideInSearch: true,
    align: 'center',
    fixed: 'right',
    width: 250,
    actions: ({ row }) => [
      {
        label: '查看',
        onClick: () => {
          console.log(row, 111111);
          state.currentData = row;
          state.showSampleSeeModal = true;
        },
      },
      {
        label: '共享',
        ifShow: state.shareState === 2,
        popConfirm: {
          title: '确认共享吗？',
          onConfirm: async () => {
            await putSampleSharing([row.id]);
            message.success('共享成功！');
            refreshTableFn();
          },
        },
      },
      {
        label: '取消共享',
        ifShow: state.shareState === 1,
        popConfirm: {
          title: '确认取消共享吗？',
          onConfirm: async () => {
            await putSampleUnSharing([row.id]);
            message.success('取消共享成功！');
            refreshTableFn();
          },
        },
      },
      {
        label: '出库',
        ifShow: state.shareState === 1,
        onClick: () => {
          router.push({
            name: 'sampleSharingOut',
            query: {
              strainIds: row.id,
            },
          });
        },
      },
    ],
  },
];
const fetchData = async (ori: VxeGridPropTypes.ProxyAjaxQueryParams) => {
  let data = superTableRef.value?.getFormModel();
  let params: API.SharedDataType = {
    pageSize: ori.page.pageSize,
    pageNum: ori.page.currentPage,
    orderBy: [
      {
        field: 'create_time',
        order: 'desc',
      },
    ],
    ...data,
  };
  let res;

  state.shareState = data.shareState;
  delete params.shareState;
  state.checkedList = [];
  switch (state.shareState) {
    case 1:
      res = await getSharedData(params);
      break;
    case 2:
      res = await getUnSharedData(params);
      break;
  }
  return res.result;
};
const refreshTableFn = () => {
  superTableRef.value?.refreshTable();
};

const checkboxChangeFn = ({ records }) => {
  state.checkedList = records;
};

/**
 * fn
 */
// 共享到收藏
const getAddMyCollectionFn = async () => {
  let params = state.checkedList?.map((item) => item.id);
  await getAddMyCollection(params);
  message.success('共享成功！');
  refreshTableFn();
};
// 取消共享
const putSampleUnSharingFn = async () => {
  let params = state.checkedList?.map((item) => item.id);
  if (state.shareState === 2) {
    await putSampleSharing(params);
    message.success('共享成功！');
  } else {
    await putSampleUnSharing(params);
    message.success('取消共享成功！');
  }
  refreshTableFn();
};
// 生成审批单
const generateApprovalTicketFn = () => {
  state.showApprovalSlipModal = true;
};
// 出库
const outboundFn = () => {
  const idList = state.checkedList?.map((item) => item.id);
  router.push({
    name: 'sampleSharingOut',
    query: {
      strainIds: idList.join(),
    },
  });
};
</script>

<style scoped lang="less"></style>
